// pages/article/rich-text/index.js
function formatRichText(html) {

  /* 
   * 处理富文本里的图片宽度自适应
   * 1.去掉img标签里的style、width、height属性
   * 2.img标签添加style属性：max-width:100%;height:auto
   * 3.修改所有style里的width属性为max-width:100%
   * 4.去掉<br/>标签
   * @param html
   * @returns {void|string|*}
   */
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    match = match.replace(/cellspacing="[^"]+"/gi, 'cellspacing="0"')
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
      'max-width:100%;');
    return match;
  });
  // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi,
    '<img style="max-width:100%;height:auto;display:inline-block;"');

  //去除table的宽度
  newContent = newContent.replace(/<table[^>]*>/gi, function (match, capture) {
    return match.replace(/width=\"(.*)\"/gi, '');

  });
  //去除cellspacing
  newContent = newContent.replace(/<table[^>]*>/gi, function (match, capture) {
    return match.replace(/cellspacing="[^"]+"/gi, 'cellspacing=0')

  });
  return newContent;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    type: 'default', //纯文字使用rich-text  带图片内容使用wxParse
    tagStyle: {
      td: 'border:none'

    },
    details: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.content) {
      var content = decodeURIComponent(options.content)
      // let html = a
      //去除table的宽度
      let html = content.replace(/cellspacing="[^"]+"/gi, 'cellspacing=0').replace(/<table[^>]*>/gi, function (match, capture) {
        return match.replace(/style="[^"]+"/gi, 'style="width:100%"');
      });
      this.setData({
        content: html,
        details: content,
        type: options.type || 'default',
        title: options.name
      })
      wx.setNavigationBarTitle({
        title: options.name,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const {
      details,
      title
    } = this.data
    return {
      title: '德道升学',
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg',
      path: `/pages/article/rich-text/index?name=${title}&content=${details}`
    }
  }
})